<template>
    <div class="app-container calendar-list-container" v-loading="loading" element-loading-text="正在导出数据">
    <!-- filter 条件查询 -->
    <div class="btn-add">
        <el-button
        icon="el-icon-circle-plus-outline"
        type="button"
        class="el-button el-button--primary"
        @click="clickShow"
        >
            新增</el-button
        >
    </div>

    <!-- 新增数据弹窗 -->
    <el-dialog
    :title="title"
    :visible.sync="showAdd"
    @close="close"
    width="60%"
    >
    <el-form :model="createForm" ref="createForm" :rules="addRules" label-width="80px">
        <el-row :gutter="20">
            <el-col :span="6">
                <el-form-item label="工作中心" prop="workCenter" >
                    <el-select clearable filterable v-model="createForm.workCenter" placeholder="请选择工作中心" @focus="getCenterList" class="ul-item">
                      <el-option :value="item" :label="item" v-for="(item,index) in this.centerList.data" :key="index"/>
                    </el-select>
                </el-form-item>
            </el-col>
            <el-col :span="5">
                <el-form-item label="提醒类别" prop="remindType" >
                    <el-select
                        v-model="createForm.remindType"
                        class="ul-item" >
                        <el-option
                            v-for="(item,index) in optionsFacilityBarcodeType"
                            :key="index"
                            :label="item"
                            :value="item">
                        </el-option>
                    </el-select>
                </el-form-item>
            </el-col>
            <el-col :span="6">
                <el-form-item label="周期 ≥" prop="period">
                    <el-input class="ul-item" clearable style="width: 130px;margin: 0 3px 0 6px;" :autosize="{ minRows: 1, maxRows: 3}" v-model="createForm.period" auto-complete="off"></el-input>{{ '天' }}
                </el-form-item>
            </el-col>
            <el-col :span="7">
                <el-form-item label="提醒频次" prop="frequency" >
                    <el-popover v-model="cronspot">
                        <cron @change="changespot" @close="cronspot=false" i18n="cn"></cron>
                        <el-input clearable style="width: 130px;margin: 0 3px 0 6px;" slot="reference" @click="cronspot=true" v-model="createForm.frequency" placeholder="请输入定时策略"></el-input>
                    </el-popover>{{ '执行一次' }}
                </el-form-item>
            </el-col>
        </el-row>
        <el-row :gutter="20">
            <el-col :span="6">
                <el-form-item label="短信提醒工段长" prop="isRemindSectionManager" label-width="120px">
                    {{ '否' }}<el-switch style="margin: 0 5px 0 5px;" v-model="createForm.isRemindSectionManager" active-value="是" inactive-value="否" />{{ '是' }}
                </el-form-item>
            </el-col>
            <el-col :span="7">
                <el-form-item label="邮件接收人" label-width="85px" >
                    <div v-for="(items,index1) in MailUserName" :key="index1" style="margin-bottom: 5px;">
                      <el-select  @change="mailChang($event,index1,1)" filterable @focus="businessFocus" v-model="items.name" placeholder="请选择" style="width:110px">
                          <el-option v-for="(item,index) in recipientsList" :key="index" :label="item.userName" :value="item.userName">
                        </el-option>
                      </el-select>
                      <el-button style="margin-left: 5px;" type="danger" icon="el-icon-delete" circle @click="delMail(index1,1)"></el-button>
                      <el-button v-if="index1 == 0" style="margin-left: 5px;" type="primary" icon="el-icon-plus" circle @click="addMail(1)"></el-button>
                    </div>
                </el-form-item>
            </el-col>
            <el-col :span="7">
                <el-form-item label="抄送人" label-width="85px" >
                    <div v-for="(items,index1) in makeName" :key="index1" style="margin-bottom: 5px;">
                      <el-select  @change="mailChang($event,index1,2)" filterable @focus="businessFocus" v-model="items.name" placeholder="请选择" style="width:110px">
                          <el-option v-for="(item,index) in recipientsList" :key="index" :label="item.userName" :value="item.userName">
                        </el-option>
                      </el-select>
                      <el-button style="margin-left: 5px;" type="danger" icon="el-icon-delete" circle @click="delMail(index1,2)"></el-button>
                      <el-button v-if="index1 == 0" style="margin-left: 5px;" type="primary" icon="el-icon-plus" circle @click="addMail(2)"></el-button>
                    </div>
                </el-form-item>
            </el-col>
        </el-row>
        </el-form>

        <!-- 公共底部 -->
        <div slot="footer" class="dialog-footer">
            <el-button @click="showAdd = false">取 消</el-button>
            <el-button
            type="primary"
            @click="addfacility('createForm')"
            >确认</el-button
            >
        </div>
    </el-dialog>


    <div class="filter-container">

        <el-select
            clearable
            filterable
            v-model="param.workCenter"
            style="margin-right: 15px" @focus="getCenterList">
            <el-option
                v-for="(item,index) in this.centerList.data"
                :key="index"
                :label="item"
                :value="item"
                placeholder="工作中心">
            </el-option>
        </el-select>

        <el-button type="primary" v-waves icon="el-icon-search" @click="getData">搜索</el-button>
        <el-button
            type="button"
            v-waves
            class="el-button el-button--warning"
            @click="cancelSubmit"
        >
        重置</el-button>
    
    </div>

    <!-- table 表格 -->
    <el-table  :data="tableInfo" v-loading="loadingList" element-loading-text="给我一首歌的时间" stripe border fit highlight-current-row style="width: 100%;margin-top:15px;">
      <el-table-column  label="序号" type="index" align="center" width="80px"/>
      <el-table-column label="工作中心"  prop="workCenter" align="center"/>
      <el-table-column label="提醒类别"  prop="remindType" align="center"/>
      <el-table-column label="周期 ≥"  prop="period" align="center"/>
      <el-table-column label="提醒频次"  prop="frequency" align="center"/>
      <el-table-column label="短信提醒工段长"  prop="isRemindSectionManager" align="center"/>
      <el-table-column label="收件人"  prop="recipientsUserName" align="center"/>
      <el-table-column label="抄送人"  prop="carbonCopyRecipientsUserName" align="center"/>
      <el-table-column label="修改时间"  prop="updateTime" align="center"/>
      <el-table-column label="修改人员"  prop="updateNumber" align="center"/>
      <el-table-column label="操作" fixed="right" align="center" width="160">
            <template slot-scope="scope" >
                <div class="fx" style="display: flex">
                    <el-button size="mini" type="primary" @click="handleEdit(scope.row)">修改</el-button>
                    <el-button
                        icon="el-icon-delete"
                        class="el-button el-button--danger"
                        style="font-size: 15px;"
                        @click="handleDelete(scope.row,scope.$index)"
                    ></el-button>
                </div>
            </template>
      </el-table-column>
    </el-table>
   
    <!-- pagination 分页 -->
    <div class="pagination-container">
      <el-pagination
        background
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="listQuery.page"
        :page-sizes="[5,10, 20, 30, 40, 100, 300, 500]"
        :page-size="listQuery.limit"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      ></el-pagination>
    </div>

    <!-- <el-divider></el-divider>   -->

    <!-- <el-button style="margin-right: 10px" type="success" size="small" @click="hExportExcel">导出数据Excel</el-button> -->

  </div>
</template>

<script>
import { wordLimitFind,wordLimitIns,updbarcodeType,wordLimitDel,getNextExecTime,wordLimitUpd } from "@/api/processRoute"
import { getCenter } from '../../api/workSection.js'
import { searchWorkers } from '../../api/chargingData.js'
import { cron } from 'vue-cron'
export default {
    template: '<cron/>',
    components: { cron },
    name: 'overdueWarning',
    data () {
        return {
            title:'新增',
            listQuery: {
                page: 1,                                    //页码
                limit: 10                                   //每页多少条记录
            },
            param: {
                facilityBarcodeType: '',                      //类型
                facilityBarcode: '',                           //工装条码   
            },
            recipientsList:[],           // 人员列表
            MailUserName:[{name:''}],    // 收件人员列表
            makeName:[{name:''}],    // 收件人员列表
            cronspot: false,        // 点检表达式弹框
            centerList: {data:[]}, 
            total: 0,                                      //数据的总数
            tableInfo: [],
            loadingList: false,
            loading: false,
            centerList: [],                         //工作中心列表
            createForm: {},
            updForm: {},
            props: { multiple: true },
            // 表单校验
            addRules: {
                workCenter: [
                    { required: true, message: "工作中心不能为空!", trigger: "change" },
                ],
                remindType: [
                    { required: true, message: "提醒类别不能为空!", trigger: "change" },
                ],
                period: [
                    { required: true, message: "周期不能为空!", trigger: "change" },
                    { validator: this.validateNumber, trigger: 'blur' }
                ],
                // frequency: [
                //     { required: true, message: "提醒频次不能为空!", trigger: "change" },
                // ],  
                isRemindSectionManager: [
                    { required: true, message: "周期不能为空!", trigger: "change" },
                ],
            },
            showAdd: false,
            showupd: false,
            userInfo: this.$store.state.user.userInfo,
            optionsFacilityBarcodeType: ['正常','预警','即将超期','已超期','严重超期']
        }
    },
    computed: {
      inputWid() {
        return function (value) {
            if(!value || (value.length <= 10)){
              return '150px'
            } else {
              return (150 + (String(value).length-10)*6) + 'px'
            }
        }
      }
    },
    methods: {
      validateNumber(rule, value, callback) {  
      // 这里使用正则表达式来校验是否只包含数字、小数点以及可能的负号  
      const regex = /^-?\d+(\.\d)?$|^-?\d+$/;  
      if (!regex.test(value)) {  
        callback(new Error('只能输入数字或保留一位小数'));  
      } else {  
        callback();  
      }  
    },  
        // 点击新增按钮
        clickShow(){
            this.title = '新增'
            this.showAdd = true
        },
        // 弹框消失
        close(){
            this.MailUserName = [{name:''}]    // 收件人员列表
            this.makeName = [{name:''}]      // 抄送人列表
            this.createForm = {isRemindSectionManager: '是'}      // 抄送人列表
            this.resetForm()
        },
        // 添加邮箱
      addMail(id){
        if(id == 1){
            if(!this.MailUserName[this.MailUserName.length -1].name){
                return this.$message.warning('请先选择人员')
            }
            this.MailUserName.push({name:''})
        } else {
            if(!this.makeName[this.makeName.length -1].name){
                return this.$message.warning('请先选择人员')
            }
            this.makeName.push({name:''})
        }
      },
      // 删除邮箱
      delMail(index,id){
        if(id == 1){
            if(this.MailUserName.length == 1){
              this.MailUserName = [{name:''}]
            } else {
              this.MailUserName.splice(index, 1);
            }
        } else {
            if(this.makeName.length == 1){
              this.makeName = [{name:''}]
            } else {
              this.makeName.splice(index, 1);
            }
        }
      },
        // 获取员工
        async businessFocus(){
        if(!this.recipientsList.length) {
          const res = await searchWorkers({page:1,limit:9999,status: 1})
          this.recipientsList = res.data.records
        }
      },
       // 邮箱发生改变
       mailChang(e,index1,id){
        this.recipientsList.forEach(item => {
          if(e){
            if(e == item.userName){
              if(item.mail && item.mail !== 'null'){
                console.log(this.recipientsList);
                if(id == 1) {
                    this.MailUserName[index1].name = item.userName
                    this.MailUserName[index1].mail = item.mail
                    this.MailUserName[index1].jobNumber = item.jobNumber
                } else {
                    this.makeName[index1].name = item.userName
                    this.makeName[index1].mail = item.mail
                    this.makeName[index1].jobNumber = item.jobNumber
                }
              } else {
                  this.$message({
                    message: `${e}没有添加邮箱！`,  
                    type: 'warning'
                  })
                  if(id == 1) {
                      this.MailUserName[index1].name = ''
                      this.MailUserName[index1].mail = ''
                      this.MailUserName[index1].jobNumber = ''
                  } else {
                    this.makeName[index1].name = ''
                    this.makeName[index1].mail = ''
                    this.makeName[index1].jobNumber = ''
                  }
              }
            }
          }
        })
      },
        // 点检表达式改变
      async changespot(val){
        let arr = val.split(" ")
        arr.pop()
        this.createForm.frequency = arr.join(" ")
        let query = {
          numTimes: 5,
          cronExpression: this.createForm.frequency
        }
        const res = await getNextExecTime(query)
         let messageContent = ''
        res.data.forEach(item => {  
        // 将每个项目添加到 messageContent 字符串中，并在每个项目后添加换行符  
        messageContent += `<div>${item}</div>`;  
      });
      // 去除字符串末尾的换行符（如果有的话）  
      if (messageContent.endsWith('\n')) {      
        messageContent = messageContent.slice(0, -1);  
      }  
        this.$message({     
          dangerouslyUseHTMLString: true,
          message: `<div>近五次的执行结果:</div>${messageContent}`,
          type: 'success',
          duration: 5000
        });
    },
         // 获取工作中心
      async getCenterList() {
        let query = {}
        const data = await getCenter(query)
        this.centerList = data
      },
        getData(){
          this.listQuery.page = 1
          this.listQuery.limit = 10
          this.handleFilter()
        },
        async handleFilter() {
            this.loadingList = true
            let query = Object.assign({},this.listQuery)
            if(this.param.workCenter){ query.workCenter = this.param.workCenter}
            let data = await wordLimitFind(query)
            let errmsg = data.msg
            this.loadingList = false
            if(data.code == '500') return
            if(data.code != '1') return this.$message.error(errmsg)
            this.total = data.data.count
            this.tableInfo = data.data.list
        },
        // table表单下方的页码组件改变每页显示的数据条数
        handleSizeChange(val) {
          this.listQuery.limit = val
          this.handleFilter()
        },
        // table表单下方的页码组件改变页面
        handleCurrentChange(val) {
          this.listQuery.page = val
          this.handleFilter()
        },
        transformDat(res) {
          const mapInfo = {
            index: '序号',
            facilityBarcodeType: '类型',
            facilityBarcodeName: '名称'
          }
          // 对data进行格式化
          // 取出所有的属性名
          const props = Object.keys(res[0]) // ['id','']
          // 将属性名从英文转为中文
          const header = props.map(zhkey => mapInfo[zhkey])
          console.log('中文的表头', header)
          // const data=[['xxxx','总裁办'，'13800000']]
          const data = res.map(obj => Object.values(obj))
          return { header, data }
        },
        // 导出excel
        async hExportExcel() {
          this.loading = true
          let query = Object.assign({},this.listQuery)
          query.page = 1
          query.limit = 10000
          if(this.param.facilityBarcodeType){ query.facilityBarcodeType = this.param.facilityBarcodeType}
          let arr = await wordLimitFind(query)
          if(arr.code == '500') return
          if(arr.code != '1'){
            this.loading = false
            return this.$message.error(errmsg)
          }
          if(!arr.data.length) return this.$message.error('暂无数据')
          const { header, data } = this.transformDat(this.setSort(arr.data))
          import('@/vendor/Export2Excel').then(excel => {
            // excel表示导入的模块对象
            console.log(excel)
            excel.export_json_to_excel({
            header, // 表头 必填
            data, // 具体数据 必填
            filename: '工装工序配置excel', // 文件名称
            autoWidth: true, // 宽度是否自适应
            bookType: 'xlsx' // 生成的文件类型
            })
          })
          this.loading = false
        },
        // 排序函数
        setSort(arr){
          let newArr = JSON.parse(JSON.stringify(arr))
          let arr1 = []
          newArr.forEach((item,index)=>{
            let obj = {
              index: index+1,
              facilityBarcodeType: item.facilityBarcodeType,
              facilityBarcodeName: item.facilityBarcodeName
            }
            arr1.push(obj)
          })
          return arr1
        },
        cancelSubmit(){
            this.param = {
                facilityBarcodeType: '',                      //类型
            }
            this.listQuery.page = 1
            this.handleFilter()
        },
        // 提交表单之前先进行验证
        addfacility(formName) {
            console.log(this.createForm)
            this.$refs[formName].validate((valid) => {
                if (valid) {
                    this.submitprocess()
                } else {
                    return false
                }
            })
        },
        async submitprocess(){  
            if(!this.createForm.frequency) return this.$message.warning('请设置点检频次')
            if(this.createForm.frequency && this.hasFirstThreeAsterisks(this.createForm.frequency)) return this.$message.warning('点检频次前三位不能有*号')
            if(!this.MailUserName[0].name) return this.$message.warning('请选择邮件接收人！')
            if(!this.makeName[0].name) return this.$message.warning('请选择抄送人！')
            let query = Object.assign({},this.createForm)
            // console.log(this.MailUserName);
            let arr1 = []
            let arr2 = []
            let arr3 = []
            let arr4 = []
            let arr5 = []
            let arr6 = []
            this.MailUserName.forEach(item => {
                arr1.push(item.name)
                arr2.push(item.jobNumber)
                arr3.push(item.mail)
            })
            this.makeName.forEach(item => {
                arr4.push(item.name)
                arr5.push(item.jobNumber)
                arr6.push(item.mail)
            })
            console.log('MailUserName',this.MailUserName)
            console.log('makeName',this.makeName)
            query.recipientsUserName = arr1.join(',')
            query.recipientsJobNumber = arr2.join(',')
            query.recipientsUserMail = arr3.join(',')
            query.carbonCopyRecipientsUserName = arr4.join(',')
            query.carbonCopyRecipientsJobNumber = arr5.join(',')
            query.carbonCopyRecipientsMail = arr6.join(';')
            
            let data
            if(this.title == '新增'){           
                data = await wordLimitIns(query)
            } else {
                data = await wordLimitUpd(query)
            }
            const errMsg = data.msg
            if(data.code == '500') return
            if(data.code != '1') return this.$message.error(errMsg)
            this.$message.success(errMsg)
            this.resetForm()
            this.showAdd = false
            this.handleFilter()
        },
        // 校验频次前三位不能是*号(不然频次太快)
        hasFirstThreeAsterisks(sty) {  
            let arr = sty.split(" ")
           // 检查数组长度是否足够  
           if (arr.length < 3) {  
               return true; // 如果数组长度小于3，则不可能前三个都有*号  
           }
           // 遍历前三个元素  
           for (let i = 0; i < 3; i++) {  
               // 如果任何一个元素不包含*号，则返回true  
               if (arr[i].includes('*')) {  
                   return true;  
               }  
           }
           // 如果所有检查都通过，则返回true  
           return false;  
       },
        resetForm(){
             this.$refs.createForm.resetFields();
        },
        handleEdit(row){
            this.title = '修改'
            this.createForm = Object.assign({},row)
            let arr1 = this.createForm.recipientsUserName.split(',')
            let arr2 = this.createForm.recipientsJobNumber.split(',')
            let arr3 = this.createForm.recipientsUserMail.split(',')  // 邮件接收人 , 
            let arr4 = this.createForm.carbonCopyRecipientsUserName.split(',')
            let arr5 = this.createForm.carbonCopyRecipientsJobNumber.split(',')
            let arr6 = this.createForm.carbonCopyRecipientsMail.split(';')  // 抄送人 ;
            this.MailUserName = arr1.map((item,index) => ({  
              name: item,
              jobNumber: arr2[index],
              mail: arr3[index],
            }))
            this.makeName = arr4.map((item,index) => ({  
              name: item,
              jobNumber: arr5[index],
              mail: arr6[index],
            }));  
            this.showAdd = true
        },
        handleDelete(row,index) {
            this.$confirm('这将会永久删除该行数据，是否继续?', '警告', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(async () => {
              await wordLimitDel({id: row.id})
              this.tableInfo.splice(index, 1)
              this.$message({
                type: 'success',
                message: '删除成功'
              })
            }).catch(() => {
                this.$message({
                  type: 'info',
                  message: '已取消删除'
                })
            })
        },
    },
    // 进入页面获取table信息
    mounted() {
        this.handleFilter()
    }
}
</script>

<style>

.btn-add{
    margin-bottom: 28px;
}

.ul-item{
  width: 85%;
}
</style>